package com.ifast.sys.controller;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.ifast.common.annotation.Log;
import com.ifast.common.base.AdminBaseController;
import com.ifast.common.domain.DictDO;
import com.ifast.common.domain.Tree;
import com.ifast.common.service.DictService;
import com.ifast.common.type.EnumErrorCode;
import com.ifast.common.utils.Const;
import com.ifast.common.utils.Result;
import com.ifast.common.utils.ShiroUtils;
import com.ifast.sys.domain.DeptDO;
import com.ifast.sys.domain.UserDO;
import com.ifast.sys.service.DeptService;
import com.xiaoleilu.hutool.util.BeanUtil;
import com.xiaoleilu.hutool.util.CollectionUtil;

import io.swagger.annotations.ApiOperation;

/**
 * <pre>
 * 部门管理
 * </pre>
 * 
 * <small> 2018年3月23日 | Aron</small>
 */
@Controller
@RequestMapping("/sys/dept")
public class DeptController extends AdminBaseController {
    private String prefix = "sys/dept";

    @Autowired
    private DeptService sysDeptService;

    @Autowired
    private DictService dictService;

    @GetMapping()
    @Log("进入部分页面")
    @RequiresPermissions("system:sysDept:sysDept")
    String dept(Model model) {
        UserDO userDO = ShiroUtils.getSysUser();
        model.addAttribute("glyDept",userDO.getDeptId());
        return prefix + "/dept";
    }

    @GetMapping("/xzDept")
    @Log("进入部分页面")
    String xzDept(Model model) {
        return prefix + "/xzDept";
    }


    @ApiOperation(value = "获取部门列表", notes = "")
    @ResponseBody
    @GetMapping("/list")
    @Log("获取部门列表")
    @RequiresPermissions("system:sysDept:sysDept")
    public Result<IPage<DeptDO>>  list(DeptDO deptDTO) {
        UserDO userDO = ShiroUtils.getSysUser();
        deptDTO.setId(userDO.getDeptId());
        IPage<DeptDO> page = sysDeptService.listPage(getPage(DeptDO.class),deptDTO);
         
        return Result.ok(page);
    }


    @GetMapping("/add/{pId}")
    @Log("进入添加部门页面")
    @RequiresPermissions("system:sysDept:add")
    String add(@PathVariable("pId") String pId, Model model) {
        model.addAttribute("pId", pId);
        model.addAttribute("pName", sysDeptService.getById(pId).getName());
        return prefix + "/add";
    }

    @GetMapping("/addChild/{pId}")
    @Log("进入添加部门页面")
    @RequiresPermissions("system:sysDept:add")
    String addChild(@PathVariable("pId") String pId, Model model) {
        model.addAttribute("pId", pId);
        model.addAttribute("pName", sysDeptService.getById(pId).getName());
        return prefix + "/addChild";
    }

    @GetMapping("/edit/{deptId}")
    @RequiresPermissions("system:sysDept:edit")
    @Log("编辑部门")
    String edit(@PathVariable("deptId") String deptId, Model model) {
        DeptDO sysDept = sysDeptService.getById(deptId);
        model.addAttribute("sysDept", sysDept);
        DeptDO parDept = sysDeptService.getById(sysDept.getParentId());
        model.addAttribute("parentDeptName", parDept.getName());
        return prefix + "/edit";
    }

    /**
     * 保存
     */
    @ResponseBody
    @PostMapping("/save")
    @RequiresPermissions("system:sysDept:add")
    @Log("保存部门")
    public Result<String> save(DeptDO sysDept) {
        sysDept.setId(Const.uuid());
        sysDeptService.save(sysDept);
        return Result.ok();
    }

    /**
     * 保存
     */
    @ResponseBody
    @PostMapping("/saveChild")
    @RequiresPermissions("system:sysDept:add")
    @Log("保存部门")
    public Result<String> saveChild(DeptDO sysDept) {
        DeptDO deptDOP =  this.sysDeptService.getById(sysDept.getParentId());
        if(deptDOP != null){
            DeptDO deptDON = new DeptDO();
            BeanUtil.copyProperties(deptDOP,deptDON);
            deptDON.setId(Const.uuid());
            deptDON.setName(sysDept.getName());
            deptDON.setOrderNum(sysDept.getOrderNum());
            deptDON.setParentId(deptDOP.getId());
            sysDeptService.save(deptDON);
            return Result.ok();
        }else{
            return Result.fail();
        }
    }

    /**
     * 修改
     */
    @ResponseBody
    @RequestMapping("/update")
    @RequiresPermissions("system:sysDept:edit")
    public Result<String> update(DeptDO sysDept) {
        sysDeptService.updateById(sysDept);
        return Result.ok();
    }

    /**
     * 删除
     */
    @PostMapping("/remove")
    @ResponseBody
    @RequiresPermissions("system:sysDept:remove")
    @Log("删除部门")
    public Result<String> remove(String id) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("parentId", id);
        int size = sysDeptService.listByMap(map).size();
        if (size > 0) {
            return Result.build(EnumErrorCode.deptUpdateErrorExistChilds.getCode(),
                    EnumErrorCode.deptUpdateErrorExistChilds.getMsg());
        }
        if (sysDeptService.checkDeptHasUser(id)) {
            sysDeptService.removeById(id);
            return Result.ok();
        } else {
            return Result.build(EnumErrorCode.deptDeleteErrorExistUsers.getCode(),
                    EnumErrorCode.deptDeleteErrorExistUsers.getMsg());
        }
    }

    /**
     * 删除
     */
    @PostMapping("/batchRemove")
    @ResponseBody
    @RequiresPermissions("system:sysDept:batchRemove")
    @Log("删除部门")
    public Result<String> remove(@RequestParam("ids[]") String[] deptIds) {
        sysDeptService.removeByIds(Arrays.asList(deptIds));
        return Result.ok();
    }

    @GetMapping("/tree")
    @ResponseBody
    @Log("查询部门树形数据")
    public Tree<DeptDO> tree() {
        String depId = ShiroUtils.getSysUser().getDeptId();
        Tree<DeptDO> tree = new Tree<DeptDO>();
        tree = sysDeptService.getTree(depId);
        return tree;
    }

    @GetMapping("/treeView")
    @Log("进入部门树形显示页面")
    String treeView() {
        return prefix + "/deptTree";
    }

}
